﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Text;
using System.Threading.Tasks;
using GurLoader.Preferences;
using Imgur.Net.Auth;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using NUnit.Framework;

namespace GurLoaderWPF.Test.Preferences
{
    [TestFixture]
    public class RegistrationTokenContextConverterTests
    {
        [Test]
        public void CanConvertTest()
        {
            var converter = new RegistrationTokenContextConverter<DefaultRegistrationTokenContext>();
            Assert.IsNotNull(converter);

            Assert.IsTrue(converter.CanConvert(typeof (DefaultRegistrationTokenContext)));
        }

        [Test]
        public void ReadJsonTest()
        {
            string jsonText =
                "{ \"AccessToken\":\"aaaa\", \"RefreshToken\":\"bbbb\", \"Expiration\":\"2014-12-12T21:32:16.3804787+09:00\" }";

            JsonReader reader = new JsonTextReader(
                new StringReader(jsonText));
            JsonSerializer serializer = new JsonSerializer();

            var converter = new RegistrationTokenContextConverter<DefaultRegistrationTokenContext>();
            Assert.IsNotNull(converter);

            var result = converter.ReadJson(
                reader, 
                typeof(DefaultRegistrationTokenContext),
                null,
                serializer );

            Assert.IsNotNull(result);
            Assert.IsInstanceOf(typeof(DefaultRegistrationTokenContext), result);
        }

        [Test]
        public void WriteJsonTest()
        {
            using (StringWriter sw = new StringWriter())
            {
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    string accessToken = "aaa";
                    string refreshToken = "rrrr";
                    DateTime expires = DateTime.Now;

                    RegistrationTokenContext tokenSet = new DefaultRegistrationTokenContext(accessToken, refreshToken,
                        expires);

                    var converter = new RegistrationTokenContextConverter<DefaultRegistrationTokenContext>();
                    Assert.IsNotNull(converter);

                    converter.WriteJson(writer, tokenSet, serializer);

                    writer.Flush();
                    string result = sw.ToString();

                    Assert.IsNotNull(result);
                    Assert.Greater(result.IndexOf(string.Format("\"AccessToken\":\"{0}\"", accessToken)), -1);
                    Assert.Greater(result.IndexOf(string.Format("\"RefreshToken\":\"{0}\"", refreshToken)), -1);
                }
            }
        }
    }
}
